import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from "./router/index.js";
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import 'highlight.js/styles/github-dark.css'

const app = createApp(App)
const pinia = createPinia()

app.use(pinia)
app.use(router)
app.use(ElementPlus)

// 初始化用户状态
import { useUserStore } from '@/stores/user'
import { authService } from '@/services/auth'

const userStore = useUserStore()

// 如果有token但没有用户信息，尝试从服务器获取
const initializeAuth = async () => {
  if (userStore.token && !userStore.user) {
    try {
      const userInfo = await authService.getCurrentUser()
      userStore.setUser(userInfo)
    } catch (error) {
      console.error('恢复用户状态失败:', error)
      // token可能已过期，清除状态
      userStore.logout()
    }
  }
}

// 异步初始化用户状态
initializeAuth()

// 页面可见性变化时检查权限
document.addEventListener('visibilitychange', async () => {
  if (!document.hidden && userStore.token) {
    try {
      // 页面重新可见时验证用户权限
      const userInfo = await authService.getCurrentUser()
      const oldPermissions = userStore.user?.permissions || []
      const newPermissions = userInfo.permissions || []
      
      // 如果权限发生变化，刷新页面
      if (JSON.stringify(oldPermissions.sort()) !== JSON.stringify(newPermissions.sort())) {
        userStore.setUser(userInfo)
        location.reload()
      }
    } catch (error) {
      console.error('权限检查失败:', error)
      userStore.logout()
      window.location.href = '/login'
    }
  }
})

app.mount('#app')
